package cn.dapeng.interview;

import cn.dapeng.util.SleepingUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 实现一个容器，提供两个方法 add和size
 * 写两个线程 线程1添加10个元素，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束??
 * <p>
 * <p>
 * <p>
 * 这种写法实现不了
 */
public class Taobao_CountDownLatch {

    volatile List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public synchronized void add(int num) {
        list.add(num);
    }

    public synchronized int size() {
        return list.size();
    }

    public static void main(String[] args) {

        CountDownLatch countDownLatch1 = new CountDownLatch(1);
        CountDownLatch countDownLatch2 = new CountDownLatch(1);

        Taobao_CountDownLatch taobao = new Taobao_CountDownLatch();

        new Thread(() -> {
            try {
                if (taobao.size() != 5) {
                    countDownLatch1.await();
                    System.out.println("t2 end");
                    countDownLatch2.countDown();
                }
            } catch (Exception e) {
                System.err.println(e);
            }
        }).start();

        SleepingUtil.sleep(2, TimeUnit.SECONDS);
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    taobao.add(i);
                    System.out.println("add" + i);
                    if(taobao.size() == 5) {
                        countDownLatch1.countDown();
                        countDownLatch2.await();
                    }
                }
            } catch (Exception e) {
                System.err.println(e);
            }

        }).start();
    }
}
